package com.javen.springbootsecurityjwt.config;

import com.javen.springbootsecurityjwt.filter.TokenAuthenticationFilter;
import com.javen.springbootsecurityjwt.filter.TokenLoginFilter;
import com.javen.springbootsecurityjwt.handler.SimpleAccessDeniedHandler;
import com.javen.springbootsecurityjwt.handler.UnauthorizedEntryPoint;
import com.javen.springbootsecurityjwt.util.DefaultPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.UUID;

/**
 * @ClassName: TokenWebSecurityConfig
 * @Description: Security核心配置类
 * @Author tujw
 * @Date 2021/1/18 10:57
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 密码管理工具类
     */
    @Autowired
    private DefaultPasswordEncoder defaultPasswordEncoder;

    /**
     * 用户服务类
     */
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 配置设置，设置退出的地址和token
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                //认证失败返回报文处理
                .authenticationEntryPoint(new UnauthorizedEntryPoint())
                //无权限返回报文处理
                .accessDeniedHandler(new SimpleAccessDeniedHandler())
                //如果这边配置了，则下面的configure方法配置的拦截规则将失效，且这边的也不能生效，可能是新版本的需要配置在configure方法中
//                .and().authorizeRequests()
//                .antMatchers("/preAuthorize").permitAll()
//                .anyRequest().authenticated()
                .and().csrf().disable()
                .logout().logoutUrl("/logout")
                .and()
                //.addLogoutHandler(new TokenLogoutHandler(tokenManager))
                //认证过滤器
                .addFilter(new TokenLoginFilter(authenticationManager()))
                //鉴权过滤器
                .addFilter(new TokenAuthenticationFilter(authenticationManager())).httpBasic();
        http.csrf().disable();
    }

    /**
     * 密码处理
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置自定义userDetailsService用户信息管理类，用于查询用户信息和权限信息；defaultPasswordEncoder为指定密码加密方式
        auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
    }

    /**
     * 配置哪些请求不拦截
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //这边加的不拦截的请求需要保证接口上面没有加权限注解，如：@PostAuthorize("hasAnyRole('ROLE_ADMIN')")，如果加了的话会以权限注解为准
        //配置了不拦截的接口，不能加@PostAuthorize注解，否则调用这个接口的时候会报An Authentication object was not found in the SecurityContext错误
        web.ignoring().antMatchers("/index**", "/api/**", "/swagger-ui.html/**", "/customer");
    }
}
